﻿using SuperX.Common.Log;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using System;

namespace SuperX.SuperSocket.Socket.Transfer.Server
{
    public class TransferServer : AppServer<TransferSession, BinaryRequestInfo>
    {
        /// <summary>
        /// 服务器当前文件上传状态的信息
        /// </summary>
        public ServerUploadStateInfo ServerUploadState = new ServerUploadStateInfo();

        public new event SessionHandler<TransferSession> NewSessionConnected;

        public TransferServer()
            : base(new DefaultReceiveFilterFactory<TransferFilter, BinaryRequestInfo>())
        {
            base.NewSessionConnected += TransferServer_NewSessionConnected;
        }

        private void TransferServer_NewSessionConnected(TransferSession session)
        {
            session.TransferServer = this;//新连接建立时，赋值TransferServer
            NewSessionConnected?.Invoke(session);
        }

        protected override void OnStopped()
        {
            base.OnStopped();
            NewSessionConnected -= TransferServer_NewSessionConnected;
        }
    }

    /// <summary>
    /// 服务器文件上传的状态信息
    /// </summary>
    [Serializable]
    public class ServerUploadStateInfo
    {
        private object lockUploadObj = new object();

        /// <summary>
        /// 类型
        /// </summary>
        public CheckUploadType CheckUploadType { get; set; }

        private bool _isUploading { get; set; }

        public string SessionID { get; set; }

        /// <summary>
        /// 执行上传的客户端的IP
        /// </summary>
        public string RemoteIP { get; set; }

        /// <summary>
        /// 获得锁
        /// </summary>
        /// <param name="sessionID"></param>
        /// <returns></returns>
        public bool GetLock(string sessionID, string remoteIP)
        {
            lock (lockUploadObj)
            {
                if (_isUploading)
                {
                    return false;
                }
                else
                {
                    Logger.Trace($"获得上传文件锁：{nameof(RemoteIP)}：{remoteIP}，{nameof(SessionID)}：{sessionID}");
                    _isUploading = true;
                    CheckUploadType = CheckUploadType.Uploading;
                    RemoteIP = remoteIP;
                    SessionID = sessionID;
                    return true;
                }
            }
        }

        /// <summary>
        /// 释放锁
        /// </summary>
        public void ReleaseLock()
        {
            Logger.Trace($"释放上传文件锁：{nameof(RemoteIP)}：{RemoteIP}，{nameof(SessionID)}：{SessionID}");
            _isUploading = false;
            CheckUploadType = CheckUploadType.None;
            RemoteIP = string.Empty;
            SessionID = string.Empty;
        }
    }

    public enum CheckUploadType
    {
        None,
        FileExists,
        Uploading,
    }
}